package com.aim.Activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aim.Service.UploadLocalService;
import com.aim.util.DBAdapter;
import com.aim.util.KeyAndValuePair;
import com.aim.util.ParseXMLString;
import com.aim.util.Preferences;
import com.aim.util.WebServiceUtil;

public class ImpoundList extends  Activity{
	static Context mC;
	DBAdapter mDBAdapter;
	private List<Map<String, Object>> mData = new ArrayList<Map<String,Object>>();
	static EditText title;
	static boolean flagSort = true, flagAll = true, flagSearch = true;
	private Button buttonsearch, buttonrefresh;
	private String result, caseno;
	private ProgressDialog progressDialog;
	
    private Handler handler = new Handler(){  
    	  
        @Override  
        public void handleMessage(Message msg) {  
              
            if(msg.what ==0)
            {
            	progressDialog.dismiss();   
            	if(flagAll)
            	setList();
            }
            else if(msg.what ==1)
            {
            	
            	progressDialog.dismiss(); 
            	if(flagSearch&&result!=null)
            	checkSearch();
            }
	             
            
        }};
	
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.impoundlist);
        mC = this;
        mDBAdapter = new DBAdapter(mC);
//        mDBAdapter.open();
        
        
//        TextView caseText = (TextView) findViewById(R.id.casetext);
//        caseText.setOnClickListener(new OnClickListener(){
//
//			public void onClick(View v) { 
//
//				sortArrayListByCaseNo(mData);
//			} 
        	
//        });
        
        
        mData = (List<Map<String, Object>>)getLastNonConfigurationInstance();
        if( mData == null ){
//        	mData = new MyData();
        	showAllCasesProgress();
          }
        else
        	setList();
        buttonsearch = (Button) findViewById(R.id.buttonsearch);
        buttonrefresh = (Button) findViewById(R.id.buttonrefresh);     
        setListener();
        Log.e("Configuration ","Create");
//        showAllCasesProgress();

        
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
//      setContentView(R.layout.myLayout);
      Log.e("Configuration ","Changed");

    } 
    @Override
    public Object onRetainNonConfigurationInstance() {
    	Log.e("dat","mdata");
    	return mData;

    }
    private void showAllCasesProgress(){
    	flagAll = true;
    
        progressDialog = new ProgressDialog(this);
        progressDialog.setButton("cancel", new DialogInterface.OnClickListener() {
        	 public void onClick(DialogInterface dialog, int i) {
        		 flagAll = false;
        	  dialog.cancel();
        	 }
        	});
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        	 public void onCancel(DialogInterface dialog) {

        	  progressDialog.dismiss();
        	  
        	 }
        	});
    	progressDialog.setCancelable(true);
    	progressDialog.setMessage("Processing, please wait!");
    	progressDialog.show();
        
        
    	new Thread(){  
    		  
            @Override  
            public void run() {  
                 
           	 downloadAllCase();
             
                handler.sendEmptyMessage(0);  
                
            }}.start();
    	
    	
             
    	
    }
    
        
    public void downloadAllCase(){
    		mDBAdapter.open();
    	
		
			SharedPreferences preferences = mC.getSharedPreferences(
					Preferences.NAME, 0);

					ArrayList parameterList = new ArrayList();
					
					String res = WebServiceUtil.callWebservice(
							"getAllAIMCaseStub", parameterList);


					
					mData = ParseXMLString.parseAllCase(res);
					
					
					
					try {
						Cursor c = mDBAdapter.fetchAllLocalCases();
						while(!c.isAfterLast()){
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("no", "Local"+c.getInt(0));
						map.put("vin",c.getString(1));
						map.put("make",c.getString(2));
						map.put("model",c.getString(3));
						map.put("color",c.getString(4));
						map.put("type",c.getString(5));
						map.put("year",c.getString(6));
						map.put("plate",c.getString(7));
						map.put("mileage",c.getString(8));
						map.put("add",c.getString(9));
						map.put("city",c.getString(10));
						map.put("state",c.getString(11));
						map.put("zip",c.getString(12));
						map.put("tow",c.getString(13));
						map.put("mark",c.getString(14));
						map.put("title",c.getString(15));
						map.put("note",c.getString(16));
						map.put("date",c.getString(17));
						map.put("noteNo","0");
						
						mData.add(map);
						
						
						c.moveToNext();
						}
						c.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					
					
		mDBAdapter.close();
    }
    


	public void searchCase(String s){
		flagSearch = true;
        progressDialog = new ProgressDialog(this);
        progressDialog.setButton("cancel", new DialogInterface.OnClickListener() {
        	 public void onClick(DialogInterface dialog, int i) {
        	  dialog.cancel();
        	 }
        	});
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        	 public void onCancel(DialogInterface dialog) {
        		 flagSearch = false;
        	  progressDialog.dismiss();
        	 }
        	});
    	progressDialog.setCancelable(true);
//        progressDialog = ProgressDialog.show(
//				mC, "Hello",
//				" Processing. Please wait ... ", true);
    	
    	progressDialog.setMessage("Processing, please wait!");
    	progressDialog.show();
        
        
//    	String resultno = null;
    	
    	caseno = s;
    	 new Thread(){  
    		  
             @Override  
             public void run() {  
            	 	ArrayList parameterList = new ArrayList();
            		KeyAndValuePair fileNamePair = new KeyAndValuePair();
            		fileNamePair.setKeyName("caseNumber");
            		fileNamePair.setKeyValue(caseno);
            		parameterList.add(0, fileNamePair);

        		result = WebServiceUtil.callWebservice(
        				"getAIMCaseDetail", parameterList);
        		    	   		Log.e("!!", "!!"+result);
    	   		handler.sendEmptyMessage(1); 
				
				
                  
                 
             }}.start();  				
			
	}
	private void checkSearch(){
		
		if(result.length()<100)
			
			Toast.makeText(mC, "Sorry, this case is not found",
	                Toast.LENGTH_LONG).show();
			
		else
			{
			
			Map<String, Object> map = new HashMap<String, Object>();
			map = ParseXMLString.parseCaseDetail(result);
			Intent editImpound = new Intent(ImpoundList.this, ImpoundTab.class);
			String no = (String)map.get("no");
			String vin = (String)map.get("vin");
			String make = (String)map.get("make");
			String model = (String)map.get("model");
			String color = (String)map.get("color");
			String type = (String)map.get("type");
			String year = (String)map.get("year");
			String imageCount = (String)map.get("imageCount");
			String add = (String)map.get("add");
			String city = (String)map.get("city");
			String state = (String)map.get("state");
			String zip = (String)map.get("zip");
			String tow = (String)map.get("tow");
			String mileage = (String)map.get("mileage");
			String plate = (String)map.get("plate");

			String date = (String)map.get("date");
			String noteNo = (String)map.get("noteNo");
			
//				int n = (Integer)mData.get(position).get("noteNo");
			if(no!=null){
				int nN = Integer.parseInt(noteNo)+1;
				
				for(int j=0; j<nN;j++)
				{
					String seqNo = (String)map.get("seqNo"+j);
					editImpound.putExtra("SEQNO"+j, seqNo);
					
					String noteTitle = (String)map.get("noteTitle"+j);
					editImpound.putExtra("NOTETITLE"+j, noteTitle);
					
					String notes = (String)map.get("notes"+j);
					editImpound.putExtra("NOTES"+j, notes);
					
					String bookmark = (String)map.get("bookmark"+j);
					editImpound.putExtra("BOOKMARK"+j, bookmark);
				
				
				}
	    		editImpound.putExtra("MODE", "edit");
	    		
	    		editImpound.putExtra("NO", no);
	    		
	    		editImpound.putExtra("VIN", vin);
	    		editImpound.putExtra("MAKE", make);
	    		editImpound.putExtra("MODEL", model);
	    		editImpound.putExtra("COLOR", color);
	    		editImpound.putExtra("TYPE", type);
	    		editImpound.putExtra("YEAR", year);
	    		editImpound.putExtra("TOW", tow);
	    		editImpound.putExtra("IMAGECOUNT", imageCount);
	    		editImpound.putExtra("MILEAGE", mileage);
	    		editImpound.putExtra("PLATE", plate);
	    		editImpound.putExtra("ADD", add);
	    		editImpound.putExtra("CITY", city);
	    		editImpound.putExtra("STATE", state);
	    		editImpound.putExtra("ZIP", zip);
	    		editImpound.putExtra("DATE", date);
	    		editImpound.putExtra("NOTENO", nN);
	    		startActivity(editImpound);
				}
			else
			{
				Toast.makeText(mC, "Sorry, this case is not found",
		                Toast.LENGTH_LONG).show();
			}

			}
		
	}
	public void sortArrayListByCaseNo(List<Map<String, Object>> mData){
		ArrayList arrayList = new ArrayList();
		for(int i = 0;i<mData.size();i++)
		{
			arrayList.add(mData.get(i).get("no"));
			
		}
		
		if(flagSort)
		Collections.sort(arrayList);
		else
			Collections.sort(arrayList,Collections.reverseOrder());
		
	    for(int i=0; i<mData.size(); i++)
	    {
	    	int j = arrayList.indexOf(mData.get(i).get("no"));
	    	

	    	Map<String, Object> temp = new HashMap<String, Object>();
	    	
	    	Map<String, Object> m1 = mData.get(i);
	    	Map<String, Object> m2 = mData.get(j);
	    	temp = m1;
	    	mData.set(i, m2);
	    	mData.set(j, temp);
	    	 
	    }
	    
	    flagSort = !flagSort;
	    setList();
	}

//    @Override
//	protected void onStop(){
//    	super.onStop();
//    	mDBAdapter.close();
//    }

    @Override
	public void finish(){
    	
    	mC = null;

    	mData= null;
    	title= null;
    	buttonsearch = null;
    	buttonrefresh = null;
    	result = null;
    	caseno = null;
    	progressDialog = null;;
//    	mDBAdapter.close();
    	super.finish();
    }  
       
    
       


    public final class ViewHolder { 
      
        public TextView listtitle; 
        public TextView listdate, listinfo; 
        public ImageView imageView;
        

    }

    public class MyAdapter extends BaseAdapter {

        private LayoutInflater mInflater;

        public MyAdapter(Context context) { 
            this.mInflater = LayoutInflater.from(context); 
        }

        
        public int getCount() { 
            // TODO Auto-generated method stub 
            return mData.size(); 
        }

         
        public Object getItem(int arg0) { 
            // TODO Auto-generated method stub 
            return null; 
        }

         
        public long getItemId(int arg0) { 
            // TODO Auto-generated method stub 
            return 0; 
        }

        
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null; 
            if (convertView == null) {

                holder = new ViewHolder();

                convertView = mInflater.inflate(R.layout.listelement2, null); 
                holder.imageView = (ImageView) convertView.findViewById(R.id.imageView1);
                holder.listtitle = (TextView) convertView.findViewById(R.id.listtitle); 
                holder.listdate = (TextView) convertView.findViewById(R.id.listdate); 
                holder.listinfo = (TextView) convertView.findViewById(R.id.listinfo); 
                

                convertView.setTag(holder);

            } else {

                holder = (ViewHolder) convertView.getTag(); 
            } 
            String a = (String)mData.get(position).get("no");
            
            if(a.startsWith("L"))
            	holder.imageView.setImageResource(R.drawable.impound_local_selected);
//            else 
//            	holder.listtitle.setTextColor(Color.GREEN);
            
//            holder.listtitle.setText("Case: "+mData.get(position).get("no")); 
//            holder.listinfo1.setText("Vin: "+mData.get(position).get("vin"));
//            holder.listinfo2.setText("Make: "+mData.get(position).get("make")+"  Model: "+mData.get(position).get("model")+"  Type: "+mData.get(position).get("type"));
           
            holder.listdate.setText(""+mData.get(position).get("date"));
            holder.listtitle.setText(""+mData.get(position).get("no")); 
            holder.listinfo.setText(mData.get(position).get("make")+"  Model:"+mData.get(position).get("model"));


            

            return convertView; 
        }
    }

    
//	@Override  
//    public boolean onCreateOptionsMenu(Menu menu) {   
//        menu.add(0,Menu.FIRST,0,"Log out");   
//        menu.add(0,Menu.FIRST+1,1,"Settings"); 
//        return super.onCreateOptionsMenu(menu);   
//           
//    }   
//	@Override  
//    public boolean onOptionsItemSelected(MenuItem item) {   
////        TextView tv = (TextView)findViewById(R.id.tv01);   
//		super.onOptionsItemSelected(item); 
//        switch(item.getItemId()){   
//            case Menu.FIRST:{
//            	Log.e("","111 pressed");
//            	
//            	break;   
//            	}
//            
//            case Menu.FIRST+1:{
//            	Intent setting = new Intent (this, Settings.class);
//            	startActivity(setting);
////            	deletePic();
//            	break;   }
//        }   
//        return true;   
//    } 

	public void setList(){
        ListView impoundlist = (ListView) findViewById(R.id.listView1);
        
        MyAdapter mAdapter = new MyAdapter(mC); 
        impoundlist.setAdapter(mAdapter); 
        impoundlist.setOnItemClickListener(new OnItemClickListener(){

			
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				Intent editImpound = new Intent(ImpoundList.this, ImpoundTab.class);
				String no = (String)mData.get(position).get("no");
				String vin = (String)mData.get(position).get("vin");
				String make = (String)mData.get(position).get("make");
				String model = (String)mData.get(position).get("model");
				String color = (String)mData.get(position).get("color");
				String type = (String)mData.get(position).get("type");
				String year = (String)mData.get(position).get("year");
				String imageCount = (String)mData.get(position).get("imageCount");
				String add = (String)mData.get(position).get("add");
				String city = (String)mData.get(position).get("city");
				String state = (String)mData.get(position).get("state");
				String zip = (String)mData.get(position).get("zip");
				String tow = (String)mData.get(position).get("tow");
				String mileage = (String)mData.get(position).get("mileage");
				String plate = (String)mData.get(position).get("plate");

				String date = (String)mData.get(position).get("date");
				
//				int n = (Integer)mData.get(position).get("noteNo");
				
				if(no.startsWith("Local"))
				{
					
					editImpound.putExtra("MODE", "local");
					String mark = (String)mData.get(position).get("mark");
					String title = (String)mData.get(position).get("title");
					String note = (String)mData.get(position).get("note");
					

	        		editImpound.putExtra("MARK", mark);
	        		editImpound.putExtra("TITLE", title);
	        		editImpound.putExtra("NOTE", note);
				}
				else
					
        		{
					editImpound.putExtra("MODE", "edit");
					String noteNo = (String)mData.get(position).get("noteNo");
					int nN = Integer.parseInt(noteNo)+1;
					for(int j=0; j<nN;j++)
					{
						String seqNo = (String)mData.get(position).get("seqNo"+j);
						editImpound.putExtra("SEQNO"+j, seqNo);
						
						String noteTitle = (String)mData.get(position).get("noteTitle"+j);
						editImpound.putExtra("NOTETITLE"+j, noteTitle);
						
						String notes = (String)mData.get(position).get("notes"+j);
						editImpound.putExtra("NOTES"+j, notes);
						
						String bookmark = (String)mData.get(position).get("bookmark"+j);
						editImpound.putExtra("BOOKMARK"+j, bookmark);
					
						
					}
					editImpound.putExtra("NOTENO", nN);
        		}
				

				
				
				
        		
        		editImpound.putExtra("NO", no);
        		
        		editImpound.putExtra("VIN", vin);
        		editImpound.putExtra("MAKE", make);
        		editImpound.putExtra("MODEL", model);
        		editImpound.putExtra("COLOR", color);
        		editImpound.putExtra("TYPE", type);
        		editImpound.putExtra("YEAR", year);
        		editImpound.putExtra("TOW", tow);
        		editImpound.putExtra("IMAGECOUNT", imageCount);
        		editImpound.putExtra("MILEAGE", mileage);
        		editImpound.putExtra("PLATE", plate);
        		editImpound.putExtra("ADD", add);
        		editImpound.putExtra("CITY", city);
        		editImpound.putExtra("STATE", state);
        		editImpound.putExtra("ZIP", zip);
        		editImpound.putExtra("DATE", date);
        		
        		startActivity(editImpound);
				
			}
        	
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	super.onActivityResult(requestCode, resultCode, intent);
        Bundle extras = intent.getExtras();

        if(requestCode==1) {

        	if(extras.getString("STOP1") != null){

        	}
        	else{}
            
        	if(extras.getString("STOP2") != null){
        		
            	}
        	else{}
        	
    		
    }    
    }
	
	private void setListener(){
		  buttonrefresh.setOnClickListener(new OnClickListener(){
	        	public void onClick (View viewParam) {
	        		showAllCasesProgress();
	        	}
	        });
		
		buttonsearch.setOnClickListener(new OnClickListener(){
        	public void onClick (View viewParam) {
        		LayoutInflater factory = LayoutInflater.from(mC);
        	   	 final View textEntryView = factory.inflate(R.layout.searchdialog, null);
        	   	
        		  title =(EditText) textEntryView.findViewById(R.id.edittextsearch);
        		    
        	   	  new AlertDialog.Builder(mC)

        	   	 .setTitle("Search Impound")
        	   	 .setView(textEntryView)
        	   	 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	   	  public void onClick(DialogInterface dialog, int whichButton) {
        	   		  
        	   		  
        	   		searchCase(title.getText()+"");
        	   		
    			
    				
    				
        	   		dialog.dismiss();
        	   	   
        	   	  }
        	   	 })
        	   	 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	   	  public void onClick(DialogInterface dialog, int whichButton) {
        	   	  /* User clicked cancel so do some stuff */
        	   		  dialog.dismiss();
        	   	  }
        	   	 })
        	   	 .create().show();
        		
        	}
        });
	}
}
